<template>
  <div class="timeline-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <Icon icon="ant-design:clock-circle-outlined" />
          专利时间脉络
        </h1>
        <p class="page-description">可视化展示专利的申请和公布时间线，帮助分析专利发展历程</p>
      </div>
      <div class="header-actions">
        <Button type="primary" @click="handleGenerateData" :loading="generating">
          <Icon icon="ant-design:reload-outlined" />
          生成数据
        </Button>
        <Button @click="handleRefresh" :loading="loading">
          <Icon icon="ant-design:reload-outlined" />
          刷新
        </Button>
      </div>
    </div>

    <!-- 筛选面板 -->
    <div class="filter-panel">
      <Card>
        <template #title>
          <Icon icon="ant-design:filter-outlined" />
          筛选条件
        </template>
        <Row :gutter="16">
          <Col :span="6">
            <FormItem label="开始日期">
              <DatePicker
                v-model:value="filterForm.startDate"
                placeholder="选择开始日期"
                style="width: 100%"
                @change="handleFilterChange"
              />
            </FormItem>
          </Col>
          <Col :span="6">
            <FormItem label="结束日期">
              <DatePicker
                v-model:value="filterForm.endDate"
                placeholder="选择结束日期"
                style="width: 100%"
                @change="handleFilterChange"
              />
            </FormItem>
          </Col>
          <Col :span="6">
            <FormItem label="事件类型">
              <Select
                v-model:value="filterForm.eventType"
                placeholder="选择事件类型"
                style="width: 100%"
                allowClear
                @change="handleFilterChange"
              >
                <SelectOption value="APPLY">申请</SelectOption>
                <SelectOption value="PUBLISH">公布</SelectOption>
                <SelectOption value="GRANT">授权</SelectOption>
                <SelectOption value="REJECT">驳回</SelectOption>
              </Select>
            </FormItem>
          </Col>
          <Col :span="6">
            <FormItem label="发明人">
              <Input
                v-model:value="filterForm.inventor"
                placeholder="输入发明人姓名"
                @change="handleFilterChange"
              />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="6">
            <FormItem label="申请机构">
              <Input
                v-model:value="filterForm.institution"
                placeholder="输入申请机构名称"
                @change="handleFilterChange"
              />
            </FormItem>
          </Col>
          <Col :span="18">
            <div class="filter-actions">
              <Button @click="handleResetFilter">重置</Button>
              <Button type="primary" @click="handleSearch">搜索</Button>
            </div>
          </Col>
        </Row>
      </Card>
    </div>

    <!-- 统计信息 -->
    <div class="stats-panel" v-if="statistics">
      <Row :gutter="16">
        <Col :span="6">
          <Card class="stat-card">
            <Statistic
              title="总专利数"
              :value="statistics.totalPatents || 0"
              :value-style="{ color: '#1890ff' }"
            >
              <template #prefix>
                <Icon icon="ant-design:file-text-outlined" />
              </template>
            </Statistic>
          </Card>
        </Col>
        <Col :span="6">
          <Card class="stat-card">
            <Statistic
              title="总事件数"
              :value="statistics.totalEvents || 0"
              :value-style="{ color: '#52c41a' }"
            >
              <template #prefix>
                <Icon icon="ant-design:clock-circle-outlined" />
              </template>
            </Statistic>
          </Card>
        </Col>
        <Col :span="6">
          <Card class="stat-card">
            <Statistic
              title="申请事件"
              :value="statistics.applicationCount || 0"
              :value-style="{ color: '#faad14' }"
            >
              <template #prefix>
                <Icon icon="ant-design:plus-circle-outlined" />
              </template>
            </Statistic>
          </Card>
        </Col>
        <Col :span="6">
          <Card class="stat-card">
            <Statistic
              title="公布事件"
              :value="statistics.publicationCount || 0"
              :value-style="{ color: '#f5222d' }"
            >
              <template #prefix>
                <Icon icon="ant-design:eye-outlined" />
              </template>
            </Statistic>
          </Card>
        </Col>
      </Row>
    </div>

    <!-- 时间脉络图表 -->
    <div class="timeline-chart">
      <Card>
        <template #title>
          <Icon icon="ant-design:bar-chart-outlined" />
          时间脉络图
        </template>
        <AdvancedTimeline
          :timeline-data="timelineData"
          :loading="loading"
          @event-click="handleEventClick"
          @view-detail="handleViewDetail"
          @view-patent="handleViewPatent"
        />
      </Card>
    </div>

    <!-- 数据可视化 -->
    <div class="data-visualization">
      <Row :gutter="16">
        <Col :span="12">
          <Card>
            <template #title>
              <Icon icon="ant-design:pie-chart-outlined" />
              年份分布
            </template>
            <DataVisualization
              :data="yearDistribution"
              type="year"
              :loading="loading"
            />
          </Card>
        </Col>
        <Col :span="12">
          <Card>
            <template #title>
              <Icon icon="ant-design:bar-chart-outlined" />
              机构统计
            </template>
            <DataVisualization
              :data="institutionStats"
              type="institution"
              :loading="loading"
            />
          </Card>
        </Col>
      </Row>
    </div>
  </div>
</template>

<script setup lang="ts" name="patent-analysis-timeLine-TimeLineIndex">
import { ref, reactive, onMounted, computed } from 'vue';
import { Card, Row, Col, Button, Form, FormItem, DatePicker, Select, SelectOption, Input, Statistic, message } from 'ant-design-vue';
import { Icon } from '/@/components/Icon';
import AdvancedTimeline from './components/AdvancedTimeline.vue';
import DataVisualization from './components/DataVisualization.vue';
import { getTimelineData, generateTimelineData, getYearDistribution, getInstitutionStats } from './TimeLine.api';
import type { PatentTimelineNode, TimelineFilter, TimelineStatistics } from './TimeLine.types';

// 响应式数据
const loading = ref(false);
const generating = ref(false);
const timelineData = ref<PatentTimelineNode[]>([]);
const statistics = ref<TimelineStatistics | null>(null);
const yearDistribution = ref<any[]>([]);
const institutionStats = ref<any[]>([]);

// 筛选表单
const filterForm = reactive<TimelineFilter>({
  startDate: undefined,
  endDate: undefined,
  eventType: undefined,
  inventor: undefined,
  institution: undefined,
});

// 加载时间脉络数据
const loadTimelineData = async () => {
  try {
    loading.value = true;
    const params = {
      startDate: filterForm.startDate ? filterForm.startDate.format('YYYY-MM-DD') : undefined,
      endDate: filterForm.endDate ? filterForm.endDate.format('YYYY-MM-DD') : undefined,
      eventType: filterForm.eventType,
      inventor: filterForm.inventor,
      institution: filterForm.institution,
    };
    
    console.log('加载时间脉络数据，参数:', params);
    const result = await getTimelineData(params);
    console.log('API返回结果:', result);
    console.log('result类型:', typeof result);
    console.log('result.timelineData存在吗:', !!result?.timelineData);
    console.log('result.result存在吗:', !!result?.result);
    
    // 处理两种可能的数据结构
    let timelineDataList = [];
    let statisticsMap = null;
    
    if (result) {
      // 情况1: result直接包含timelineData和statistics
      if (result.timelineData) {
        timelineDataList = result.timelineData;
        statisticsMap = result.statistics;
      }
      // 情况2: result.result包含timelineData和statistics
      else if (result.result) {
        timelineDataList = result.result.timelineData || [];
        statisticsMap = result.result.statistics || null;
      }
      
      console.log('时间脉络数据数量:', timelineDataList.length);
      console.log('统计数据:', statisticsMap);
      
      timelineData.value = timelineDataList;
      statistics.value = statisticsMap;
      
      if (timelineDataList.length === 0) {
        message.warning('未找到符合条件的时间脉络数据');
      }
    } else {
      console.error('API返回失败:', result);
      message.error('加载时间脉络数据失败');
    }
  } catch (error) {
    console.error('加载时间脉络数据失败:', error);
    message.error('加载时间脉络数据失败: ' + (error.message || '未知错误'));
  } finally {
    loading.value = false;
  }
};

// 加载统计数据
const loadStatistics = async () => {
  try {
    const params = {
      startDate: filterForm.startDate ? filterForm.startDate.format('YYYY-MM-DD') : undefined,
      endDate: filterForm.endDate ? filterForm.endDate.format('YYYY-MM-DD') : undefined,
    };
    
    const [yearResult, institutionResult] = await Promise.all([
      getYearDistribution(params),
      getInstitutionStats(params),
    ]);
    
    if (yearResult.success) {
      yearDistribution.value = yearResult.result || [];
    }
    if (institutionResult.success) {
      institutionStats.value = institutionResult.result || [];
    }
  } catch (error) {
    console.error('加载统计数据失败:', error);
  }
};

// 生成时间脉络数据
const handleGenerateData = async () => {
  let loadingMessage = null;
  try {
    generating.value = true;
    loadingMessage = message.loading('正在生成时间脉络数据，请稍候...', 0); // 显示加载消息
    
    const result = await generateTimelineData();
    
    // 确保清除加载消息
    if (loadingMessage) {
      loadingMessage();
    }
    message.destroy();
    
    if (result.success) {
      message.success('时间脉络数据生成成功');
      await loadTimelineData();
      await loadStatistics();
    } else {
      message.error(result.message || '生成时间脉络数据失败');
    }
  } catch (error) {
    console.error('生成时间脉络数据失败:', error);
    
    // 确保清除加载消息
    if (loadingMessage) {
      loadingMessage();
    }
    message.destroy();
    
    if (error.message && error.message.includes('timeout')) {
      message.error('生成数据超时，请稍后重试或联系管理员');
    } else {
      message.error('生成时间脉络数据失败: ' + (error.message || '未知错误'));
    }
  } finally {
    generating.value = false;
    // 最后再次确保清除所有消息
    message.destroy();
  }
};

// 刷新数据
const handleRefresh = async () => {
  await loadTimelineData();
  await loadStatistics();
};

// 筛选条件变化
const handleFilterChange = () => {
  // 可以添加防抖逻辑
};

// 搜索
const handleSearch = () => {
  loadTimelineData();
  loadStatistics();
};

// 重置筛选
const handleResetFilter = () => {
  Object.assign(filterForm, {
    startDate: undefined,
    endDate: undefined,
    eventType: undefined,
    inventor: undefined,
    institution: undefined,
  });
  loadTimelineData();
  loadStatistics();
};

// 事件点击
const handleEventClick = (event: PatentTimelineNode) => {
  console.log('事件点击:', event);
};

// 查看详情
const handleViewDetail = (event: PatentTimelineNode) => {
  console.log('查看详情:', event);
  message.info(`查看事件详情: ${event.title}`);
};

// 查看专利
const handleViewPatent = (event: PatentTimelineNode) => {
  console.log('查看专利:', event);
  message.info(`查看专利: ${event.patentId}`);
};

// 组件挂载
onMounted(() => {
  loadTimelineData();
  loadStatistics();
});
</script>

<style scoped lang="less">
.timeline-container {
  padding: 24px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-content {
  .page-title {
    display: flex;
    align-items: center;
    gap: 12px;
    margin: 0 0 8px 0;
    font-size: 24px;
    font-weight: 600;
    color: #262626;
  }
  
  .page-description {
    margin: 0;
    color: #8c8c8c;
    font-size: 14px;
  }
}

.header-actions {
  display: flex;
  gap: 12px;
}

.filter-panel {
  margin-bottom: 24px;
  
  .filter-actions {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
    margin-top: 24px;
  }
}

.stats-panel {
  margin-bottom: 24px;
  
  .stat-card {
    text-align: center;
    
    :deep(.ant-statistic-title) {
      color: #8c8c8c;
      font-size: 14px;
    }
    
    :deep(.ant-statistic-content) {
      font-size: 24px;
      font-weight: 600;
    }
  }
}

.timeline-chart {
  margin-bottom: 24px;
}

.data-visualization {
  .ant-card {
    height: 400px;
  }
}
</style>
